#include "game_widget.h"

#include <QMouseEvent>
#include <QApplication>

GameWidget::GameWidget(QWidget *parent, std::shared_ptr<tcp_client> client) :
    QWidget(parent),
    mineSweeperWidgetPtr_(std::make_shared<MineSweeprWidget>(this)),
    clientPtr_(client),
    timerLabel_(this),
    scoreBoardPlayer1_(this),
    scoreBoardPlayer2_(this),
    click_all_pos_(this)
{
    setFixedSize(MINESWEEPER_WIDGET_LENTH + GAME_WIDGET_SIDE_WIDGET_WIDTH, MINESWEEPER_WIDGET_WIDTH);
    mineSweeperWidgetPtr_->setTcpClient(client);
    mineSweeperWidgetPtr_->show();

    setTimerLabel();

    scoreBoardPlayer1_.move(MINESWEEPER_WIDGET_LENTH, 30);
    scoreBoardPlayer1_.show();
    scoreBoardPlayer2_.move(MINESWEEPER_WIDGET_LENTH, 200);
    scoreBoardPlayer2_.show();

    connect(&timer_, &QTimer::timeout, this, [this]() {
        seconds_++;
        timerLabel_.setText(QString::number(seconds_));
    });

    connect(this, &GameWidget::showWindow, this, [this]() {
        this->show();
        this->timer_.start(1000);
    });

    connect(this, &GameWidget::showGameResultDiag, this, [this]() {
        
        gameResultDialog_.exec();
    });

    connect(this, &GameWidget::refreshScoreBoard, this, [this]() {
        /* refresh player1 score board */
        auto &p1 = mineSweeperWidgetPtr_->player1();
        scoreBoardPlayer1_.setOpenedBombsNum(p1.openedBombsNum());
        scoreBoardPlayer1_.setOpenedNotBombsNum(p1.openedNotBombsNum());
        scoreBoardPlayer1_.setScore(p1.score());

        scoreBoardPlayer1_.refresh();

        /* refresh player2 score board */
        auto &p2 = mineSweeperWidgetPtr_->player2();
        scoreBoardPlayer2_.setOpenedBombsNum(p2.openedBombsNum());
        scoreBoardPlayer2_.setOpenedNotBombsNum(p2.openedNotBombsNum());
        scoreBoardPlayer2_.setScore(p2.score());

        scoreBoardPlayer2_.refresh();
    });

    connect(&click_all_pos_, &QPushButton::clicked, this, [this]() {
        for (int i = 0; i < mineSweeperWidgetPtr_->rowNum(); i++) {
            for (int j = 0; j < mineSweeperWidgetPtr_->colNum(); j++) {
                int rowBase = 15;
                int colBase = 15;
                /* TODO: */
                QMouseEvent pressEvent(QEvent::MouseButtonPress, 
                      QPointF(rowBase + j * 30, colBase + i * 30), 
                      Qt::LeftButton, 
                      Qt::LeftButton, 
                      Qt::NoModifier);
                QApplication::sendEvent(mineSweeperWidgetPtr_.get(), &pressEvent);
            }
        }
    });

    click_all_pos_.move(MINESWEEPER_WIDGET_LENTH, 0);
}
